package com.simba.server.base;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class CommonUtil
{
	private CommonUtil(){}
	private static Gson gson;
	public static boolean doAnalysisBatchResult(int[] result)
	{
		boolean ret = false;
		for (int res : result)
		{
			if (res > 0)
			{
				ret = true;
			}
			else
			{
				ret = false;
				break;
			}
		}
		return ret;
	}

	public static String doNullData(String data, String defaultData)
	{
		return isNull(data) ? defaultData : data;
	}

	public static String getRandom(Long position)
	{
		Random r = new Random();
		long num = Math.abs(r.nextLong() % position);
		String s = String.valueOf(num);
		for (int i = 0; i < String.valueOf(position).length() - 1 - s.length(); i++)
		{
			s = "0" + s;
		}

		return s;
	}

	public static int getSlotId(List<Integer> slots, int defaultId)
	{
		try
		{
			if (slots != null && slots.size() > 0)
			{
				if (slots.size() == 1)
				{
					return slots.get(0);
				}
				else
				{
					return slots.get(new Random().nextInt(slots.size()));
				}
			}
		}
		catch (Exception e)
		{
			return defaultId;
		}
		return defaultId;
	}

	public static boolean isNull(String str)
	{
		return str == null || str.trim().equals("null") || str.trim().equals("");
	}

	public static String StringToDate(String dateStr)
	{
		if (dateStr.length() == 14 || dateStr.length() == 8)
		{
			return dateStr;
		}
		else if (dateStr.length() == 12)
		{
			return dateStr + "00";
		}
		else
		{
			return "00000000";
		}
	}

	public static Gson getGson(){
		if (gson == null){
			GsonBuilder gsonBuilder = new GsonBuilder();
//			gsonBuilder.setPrettyPrinting();
			gsonBuilder.serializeNulls();
			gson = gsonBuilder.create();
		}
		return gson;
	}


	public static <T extends Comparable<? super T>> boolean equalLists(List<T> one, List<T> two){
		if (one == null && two == null){
			return true;
		}

		if(one == null || two == null || one.size() != two.size()){
			return false;
		}

		one = new ArrayList<>(one);
		two = new ArrayList<>(two);

		Collections.sort(one);
		Collections.sort(two);

		return one.equals(two);
	}

	public static String formatZero(String str, int digit)
	{
		int strLen = str.length();
		int zeroLen = digit - strLen;
		if (zeroLen < 0)
		{
			return str;
		}
		StringBuilder zero = new StringBuilder();
		for (int i = 0; i < zeroLen; i++)
		{
			zero.append("0");
		}
		return zero + str;
	}
}
